package com.cmcc.aregister.ui.activity;

import java.io.IOException;
import java.net.URL;
import java.util.Map;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

import com.cmcc.aregister.Controller;
import com.cmcc.aregister.MyApplication;
import com.cmcc.aregister.R;
import com.cmcc.aregister.cs.constant.Arguments;
import com.cmcc.aregister.cs.constant.ConfigUtilHelper;
import com.cmcc.aregister.cs.database.DatabaseAdapter;
import com.cmcc.aregister.cs.database.IDatabase;
import com.cmcc.aregister.cs.util.MyLogger;
import com.cmcc.aregister.cs.util.PotoalParcelable;
import com.cmcc.aregister.cs.util.Utils;
import com.cmcc.aregister.ui.dialog.SingleAlertDialog;
import com.cmcc.aregister.ui.view.Rotate3dAnimation;
import com.cmcc.sdk.CmccDataStatistics;

public class LoginParentActivity extends Activity
{
    protected static final MyLogger logger = MyLogger.getLogger();
    protected Context context;
    // 对话框参数
    protected Dialog dialog;
    protected Controller mHttpManager = null;
    protected IDatabase database;

    protected MyApplication app;

    // UpdateEntity entity;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        MyApplication.getInstance().addActivity(this);
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        CmccDataStatistics.onStop(this);
        dismissProgressDialog();
        setTaskHandlerNull();
    }

    protected void setTaskHandlerNull()
    {
    };

    @Override
    protected void onRestart()
    {
        super.onRestart();
    }

    @Override
    protected void onResume()
    {
        super.onResume();
        CmccDataStatistics.onStart(this);
    }

    @Override
    protected void onStart()
    {
        super.onStart();
    }

    @Override
    protected void onStop()
    {
        super.onStop();
    }

    public void showProgressDialog()
    {
        if (dialog != null && dialog.isShowing())
        {
            return;
        }
        showProgressDialog(R.string.notice,
            getString(R.string.dialog_reading_info));
    }

    public void showProgressDialogUpdate()
    {
        if (dialog != null && dialog.isShowing())
        {
            return;
        }
        showProgressDialog(R.string.notice,
            getString(R.string.dialog_update_msg));
    }

    public void showProgressDialogNew(int id)
    {
        if (dialog != null && dialog.isShowing())
        {
            return;
        }
        showProgressDialog(R.string.notice, getString(id));
    }

    protected void showProgressDialog(int title, String msg)
    {
        dialog = new ProgressDialog(this);
        ((ProgressDialog) dialog)
            .setProgressStyle(ProgressDialog.STYLE_SPINNER);
        dialog.setTitle(title);
        ((ProgressDialog) dialog).setMessage(msg);
        if (null != dialog && !dialog.isShowing())
        {
            try
            {
                dialog.show();
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    protected void dismissProgressDialog()
    {
        if (null != dialog && dialog.isShowing())
        {
            try
            {
                dialog.dismiss();
                dialog = null;
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    public void init(int layoutId)
    {
        context = this;
        app = MyApplication.getInstance();
        mHttpManager = Controller.getInstance();
        mHttpManager.setCxt(this);
        database = app.getIDatabase();
        setContentView(layoutId);
        setupData();
        setupView();
    }

    protected void setupData()
    {

    }

    protected void setupView()
    {
    }

    public void showMsg(int strId)
    {
        Toast.makeText(context, strId, Toast.LENGTH_SHORT).show();
    }

    /**
     * 切到下一个页面
     * 
     * @param map
     * @param name
     */
    public void accessNextPage(Map<String, Object> map, Class<?> name)
    {
        PotoalParcelable potoal = new PotoalParcelable(map);
        Intent intent = new Intent(this, name);
        intent.putExtra(Arguments.INTENT_TO_NEXT_PAGE, potoal);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    /**
     * 切到下一个页面
     * 
     * @param name
     */
    public void accessNextPage(Class<?> name)
    {
        Intent intent = new Intent(this, name);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    /**
     * 启动3d动画
     * 
     * @param view
     */
    protected void start3DAnimation(View view)
    {
        final float centerX = view.getWidth() / 2.0f;
        final float centerY = view.getHeight() / 2.0f;
        Rotate3dAnimation rotation = new Rotate3dAnimation(0, 90, centerX,
            centerY, 310.0f, false);
        rotation.setDuration(500);
        rotation.setFillAfter(true);
        rotation.setInterpolator(new DecelerateInterpolator());
        rotation.setAnimationListener(new DisplayNextView(view));
        view.startAnimation(rotation);
    }

    /**
     * 动画监听
     * 
     * @author Administrator
     * 
     */
    protected final class DisplayNextView implements
        Animation.AnimationListener
    {
        private View view;

        public DisplayNextView(View view)
        {
            this.view = view;
        }

        public void onAnimationStart(Animation animation)
        {
        }

        public void onAnimationEnd(Animation animation)
        {
            view.post(new SwapViews(view));
            animHandler.sendEmptyMessage(0);
        }

        public void onAnimationRepeat(Animation animation)
        {
        }
    }

    /**
     * 继续旋转
     * 
     * @author Administrator
     * 
     */
    protected final class SwapViews implements Runnable
    {
        private View view;

        public SwapViews(View view)
        {
            this.view = view;
        }

        public void run()
        {
            final float centerX = view.getWidth() / 2.0f;
            final float centerY = view.getHeight() / 2.0f;
            Rotate3dAnimation rotation;
            rotation = new Rotate3dAnimation(-90, 0, centerX, centerY, 310.0f,
                false);
            rotation.setDuration(500);
            rotation.setFillAfter(true);
            rotation.setInterpolator(new DecelerateInterpolator());
            view.startAnimation(rotation);
        }
    }

    Handler animHandler = new Handler() {
        @Override
        public void handleMessage(Message msg)
        {
            animFrushView();
        }
    };

    /**
     * 旋转到-90度时刷新页面
     */
    public void animFrushView()
    {

    }

    /**
     * 
     * @param id
     * @param hasBtn 是否有按钮
     */
    // protected void showInfoDialog(int id, boolean hasBtn)
    // {
    // try
    // {
    // // dialog = new MyInfoDialog(this, hasBtn);
    // // ((MyInfoDialog) dialog).setText(id);
    // dialog = showSingleAlertDlg(id);
    // if (dialog != null)
    // {
    // if (dialog.isShowing())
    // {
    // dialog.dismiss();
    // }
    // dialog.show();
    // }
    // }
    // catch (Exception e)
    // {
    // e.printStackTrace();
    // }
    // }

    protected void showInfoDialog(int id, OnClickListener onClickListener)
    {
        try
        {
            dialog = showSingleAlertDlg(id, onClickListener);
            if (dialog != null)
            {
                if (dialog.isShowing())
                {
                    dialog.dismiss();
                }
                dialog.show();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    protected void showInfoDialog(String str, OnClickListener onClickListener)
    {
        try
        {
            dialog = showSingleAlertDlg(str, onClickListener);
            if (dialog != null)
            {
                if (dialog.isShowing())
                {
                    dialog.dismiss();
                }
                dialog.show();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    protected void _showInfoDialog(String str, OnClickListener onClickListener)
    {
        try
        {
            dialog = showSingleAlertDlg(str, onClickListener);
            if (dialog != null)
            {
                if (dialog.isShowing())
                {
                    dialog.dismiss();
                }
                dialog.show();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {

            @Override
            public void onDismiss(DialogInterface dialog)
            {
                // TODO Auto-generated method stub
                doSomeWork();
            }

        });
    }

    public void doSomeWork()
    {
    };

    // protected void showInfoDialog(String str, boolean hasBtn)
    // {
    // try
    // {
    // // dialog = new MyInfoDialog(this, hasBtn);
    // // ((MyInfoDialog) dialog).setText(str);
    // dialog = showSingleAlertDlg(str);
    // if (dialog != null)
    // {
    // if (dialog.isShowing())
    // {
    // dialog.dismiss();
    // }
    // dialog.show();
    // }
    // }
    // catch (Exception e)
    // {
    // e.printStackTrace();
    // }
    // }

    public Dialog showSingleAlertDlg(int msg)
    {
        return new AlertDialog.Builder(this)
            .setTitle(R.string.notice)
            .setMessage(msg)
            .setIcon(android.R.drawable.ic_dialog_info)
            .setCancelable(true)
            .setPositiveButton(R.string.dialog_close,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                    }
                }).create();
    }

    public Dialog showSingleAlertDlg(int msg, OnClickListener onClickListener)
    {
        return new AlertDialog.Builder(this).setTitle(R.string.notice)
            .setMessage(msg).setIcon(android.R.drawable.ic_dialog_info)
            .setCancelable(true)
            .setPositiveButton(R.string.dialog_close, onClickListener).create();
    }

    public Dialog showSingleAlertDlg(String msg, OnClickListener onClickListener)
    {
        return new AlertDialog.Builder(this).setTitle(R.string.notice)
            .setMessage(msg).setIcon(android.R.drawable.ic_dialog_info)
            .setCancelable(true)
            .setPositiveButton(R.string.dialog_close, onClickListener).create();
    }

    public Dialog showSingleAlertDlg_(String msg,
        OnClickListener onClickListener)
    {
        return new AlertDialog.Builder(this).setTitle(R.string.notice)
            .setMessage(msg).setIcon(android.R.drawable.ic_dialog_info)
            .setCancelable(false)
            .setPositiveButton(R.string.dialog_close, onClickListener).create();
    }

    public Dialog showSingleNoticeDlg(String msg,
        OnClickListener onClickListener)
    {
        return new AlertDialog.Builder(this).setTitle(R.string.notice)
            .setMessage(msg).setIcon(android.R.drawable.ic_dialog_info)
            .setCancelable(true)
            .setPositiveButton(R.string.know, onClickListener).create();
    }

    public Dialog showSingleAlertDlg(String msg)
    {
        return new AlertDialog.Builder(this)
            .setTitle(R.string.notice)
            .setMessage(msg)
            .setIcon(android.R.drawable.ic_dialog_info)
            .setCancelable(true)
            .setPositiveButton(R.string.dialog_close,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                    }
                }).create();
    }

    // protected void showConfirmDialog(int str) {
    // try {
    // dialog = new MyConfirmDialog(this);
    // ((MyConfirmDialog) dialog).setText(str);
    // if (dialog != null) {
    // dialog.show();
    // }
    // } catch (Exception e) {
    // e.printStackTrace();
    // }
    // }
    protected void showConfirmDialog(int str)
    {
        try
        {
            dialog = new AlertDialog.Builder(this)
                .setTitle(R.string.notice)
                .setMessage(str)
                .setIcon(android.R.drawable.ic_dialog_info)
                .setCancelable(true)
                .setPositiveButton(R.string.confirm,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which)
                        {
                            dialog.dismiss();
                            MyApplication app = (MyApplication) getApplication();
                            app.etime = System.currentTimeMillis() / 1000;
                            ConfigUtilHelper.countLiuliang(app);
                            ConfigUtilHelper.saveStime(app, app.stime);
                            ConfigUtilHelper.saveEtime(app, app.etime);
                            ConfigUtilHelper.saveNetworkState(app,
                                ConfigUtilHelper.checkNetworkState(app));

                            DatabaseAdapter mDatabaseAdapter = new DatabaseAdapter(
                                context);
                            mDatabaseAdapter.open_user();
                            mDatabaseAdapter.deleteAllUserData();
                            mDatabaseAdapter.close_user();
                            Utils.exitProgram();

                            // finish();
                        }
                    })
                .setNeutralButton(R.string.cancel,
                    new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which)
                        {
                            dialog.dismiss();
                        }
                    }).create();
            if (dialog != null)
            {
                dialog.show();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 判断网络连接
     * 
     * @return
     */
    public boolean connectedNetwork()
    {
        ConnectivityManager manager = (ConnectivityManager) this
            .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = manager.getActiveNetworkInfo();
        if (info == null || !info.isConnected())
        {
            return false;
        }
        if (info.isRoaming())
        {
            return true;
        }
        return true;
    }

    public void showSingleAlertDlg(String title, String msg, String posTitle)
    {
        try
        {

            if (context == null)
            {
                context = getParent();
            }
            dialog = new SingleAlertDialog(context, title, msg, posTitle);
            if (dialog != null)
            {
                dialog.show();
            }
        }
        catch (Exception e)
        {
            // TODO: handle exception
        }
    }

    public void singleBtnWork()
    {
    }

    public void showSingleAlertDlg(String title, String msg, String posTitle,
        final boolean needClose)
    {
        new AlertDialog.Builder(this).setTitle(title).setMessage(msg)
            .setIcon(android.R.drawable.ic_dialog_alert).setCancelable(false)
            .setPositiveButton(posTitle, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    // TODO Auto-generated method stub
                    singleBtnWork(needClose);
                }
            }).create().show();
    }

    public void singleBtnWork(boolean needClose)
    {
        if (needClose)
        {
            finish();
        }
    }

    private void gotoMore()
    {
        Intent intent = new Intent(this, MainActivity.class);
        int menu_id = 4;
        intent.putExtra(Arguments.INTENT_TO_MAIN_ID, menu_id);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_MENU)
        {
            // 在这里做你想做的事情
            // super.openOptionsMenu(); // 调用这个，就可以弹出菜单
            // gotoMore();
            return true;
        }
        return super.onKeyDown(keyCode, event); // 最后，一定要做完以后返回
                                                // true，或者在弹出菜单后返回true，其他键返回super，让其他键默认

    }

    @Override
    public void onOptionsMenuClosed(Menu menu)
    {
        // 关闭Menu菜单时你想做的事情

        super.onOptionsMenuClosed(menu);
    }

    boolean flag = false;

    public void showProgressDlgP(String title, String msg)
    {

        final ProgressDialog loadingDlg = new ProgressDialog(this);
        loadingDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        loadingDlg.setTitle(title);
        loadingDlg.setMessage(msg);
        loadingDlg.setIcon(android.R.drawable.ic_dialog_info);
        loadingDlg.setCancelable(true);
        loadingDlg.show();
        new Thread() {
            public void run()
            {
                try
                {
                    progressRunP();
                    flag = true;
                }
                catch (Exception e)
                {
                    loadingDlg.dismiss();
                }
                loadingDlg.dismiss();
            }
        }.start();
        loadingDlg
            .setOnDismissListener(new DialogInterface.OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface dialog)
                {
                    // TODO Auto-generated method stub
                    if (flag)
                    {
                        flag = false;
                        doWorkP();
                    }
                }

            });
    }

    public void progressRunP()
    {
    };

    public void doWorkP()
    {
    };

    public void showDoubleDlg(String title, String msg, String posTitle,
        String nagativeTitle)
    {
        new AlertDialog.Builder(this)
            .setTitle(title)
            .setMessage(msg)
            .setIcon(android.R.drawable.ic_dialog_info)
            .setCancelable(true)
            .setPositiveButton(posTitle, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    doPWork();
                }
            })
            .setNegativeButton(nagativeTitle,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {

                    }

                }).create().show();
    }

    public void doPWork()
    {
    }

    /**
     * 双选框，目前用于首页询问是否注册
     * @param title
     * @param msg
     * @param posTitle
     * @param nagativeTitle
     */
    public void showDoubleDlg_(String title, String msg, String posTitle,
        String nagativeTitle)
    {
        // new AlertDialog.Builder(this)
        // .setTitle(title)
        // .setMessage(msg)
        // .setIcon(android.R.drawable.ic_dialog_info)
        // .setCancelable(false)
        // .setPositiveButton(posTitle, new DialogInterface.OnClickListener() {
        // @Override
        // public void onClick(DialogInterface dialog, int which)
        // {
        // doPWork_();
        // }
        // })
        // .setNegativeButton(nagativeTitle,
        // new DialogInterface.OnClickListener() {
        //
        // @Override
        // public void onClick(DialogInterface dialog, int which)
        // {
        // doBackIndex();
        // }
        //
        // }).create().show();

    }

    public void doPWork_()
    {
    }

    public void doBackIndex()
    {
    }

    /**
     * 选择确认对话框
     * @param title
     * @param msg
     * @param posTitle
     * @param nagativeTitle
     */
    public void _showDoubleDlg(String title, String msg, String posTitle,
        String nagativeTitle)
    {
        new AlertDialog.Builder(this)
            .setTitle(title)
            .setMessage(msg)
            .setIcon(android.R.drawable.ic_dialog_info)
            .setCancelable(true)
            .setPositiveButton(posTitle, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    _doPWork();
                }
            })
            .setNegativeButton(nagativeTitle,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {

                    }

                }).create().show();
    }

    public void _doPWork()
    {
    }

    /**
     * 选择确认对话框
     * @param title
     * @param msg
     * @param posTitle
     * @param nagativeTitle
     */
    public void showDoubleDlg_UpdFmmily(String title, String msg,
        String posTitle, String nagativeTitle)
    {
        new AlertDialog.Builder(this)
            .setTitle(title)
            .setMessage(msg)
            .setIcon(android.R.drawable.ic_dialog_info)
            .setCancelable(true)
            .setPositiveButton(posTitle, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    doPWork_UpdFmmily();
                }
            })
            .setNegativeButton(nagativeTitle,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {

                    }

                }).create().show();
    }

    public void doPWork_UpdFmmily()
    {
    }

    /**
     * 隐藏软件盘
     * @param a
     */
    public void closeSoftKeys(Activity a)
    {
        ((InputMethodManager) a.getSystemService(INPUT_METHOD_SERVICE))
            .hideSoftInputFromWindow(a.getCurrentFocus().getWindowToken(),
                InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 强制更新对话框
     * @param title
     * @param msg
     * @param posTitle
     * @param str_url
     */
    public void showAlert_update(String title, String msg, String posTitle,
        final String str_url)
    {
        new AlertDialog.Builder(this).setTitle(title).setMessage(msg)
            .setIcon(android.R.drawable.ic_dialog_alert).setCancelable(false)
            .setPositiveButton(posTitle, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    nagativeDoWorkUpdate(str_url);
                }
            }).create().show();
    }

    /**
     * 检查更新对话框
     * @param title
     * @param msg
     * @param posTitle
     * @param nagativeTitle
     */
    public void showAlertDlg_update(String title, String msg, String posTitle,
        String nagativeTitle, final String str_url)
    {
        LayoutInflater factory = LayoutInflater.from(this);
        final View view = factory.inflate(R.layout.dialog_view_layout, null);
        TextView markTxt = (TextView) view.findViewById(R.id.mark_txt);
        markTxt.setText(msg);
        new AlertDialog.Builder(this)
            .setTitle(title)
            .setIcon(android.R.drawable.ic_dialog_info)
            .setCancelable(true)
            .setView(view)
            .setPositiveButton(posTitle, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    // TODO Auto-generated method stub
                    positiveDoworkUpdate();
                }
            })
            .setNegativeButton(nagativeTitle,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        // TODO Auto-generated method stub
                        nagativeDoWorkUpdate(str_url);
                    }

                }).create().show();
    }

    public void positiveDoworkUpdate()
    {

    }

    public void nagativeDoWorkUpdate(String url)
    {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse(url);
        intent.setData(content_url);
        startActivity(intent);
    }

    /**
     * 根据地址获取图片drawable
     * @param urladdr
     * @return
     */
    public Drawable loadImageFromNetwork(String urladdr)
    {
        // TODO Auto-generated method stub
        Drawable drawable = null;
        try
        {
            // judge if has picture locate or not according to filename
            drawable = Drawable.createFromStream(new URL(urladdr).openStream(),
                "image.jpg");
        }
        catch (IOException e)
        {
            Log.i("NewIndexActivity", "加载图片时，服务器未找到对应的路径", e);
        }
        return drawable;
    }
}
